var express = require('express');
var router = express.Router();
const { userModel, VerificationCodeModel } = require('../database/database');
const jwt = require('jsonwebtoken');
const secret = '123456';
const nodemailer = require('nodemailer');

const generateAccessToken = (user) => {
  return jwt.sign({ id: user._id }, secret, {
    expiresIn: '15m'
  });
};

const generateRefreshToken = (user) => {
  return jwt.sign({ id: user._id }, secret, {
    expiresIn: '7d'
  });
};

// 用户注册接口
router.post('/register', async (req, res) => {
  try {
    const { username, password, email } = req.body;
    if (!username || !password) {
      return res.status(400).json({ code: 400, message: '用户名和密码不能为空' });
    }

    // 检查用户是否已存在
    const existingUser = await userModel.findOne({ username });
    if (existingUser) {
      return res.status(400).json({ code: 400, message: '用户名已存在' });
    }

    // 创建新用户
    const newUser = new userModel({
      username,
      password,
      email: email || '',
      createdAt: new Date(),
      //用户的基本信息
      target: '',
      gender: '',
      age: '',
      bloodSign: '',
      bloodType: '',
      weight: '',
      weightUnit: '',
      createtime: ''
    });

    await newUser.save();
    res.json({ code: 200, message: '注册成功' });

  } catch (error) {
    console.error('Register Error:', error);
    res.status(500).json({ code: -1, message: '服务器错误，请稍后再试' });
  }
});

// 用户登录接口
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    if (!username || !password) {
      return res.status(400).json({ code: 400, message: '用户名和密码不能为空' });
    }

    const user = await userModel.findOne({ username, password, });
    if (!user) {
      return res.status(400).json({ code: 400, message: '用户名或密码错误' });
    }

    const accessToken = generateAccessToken(user);
    const refreshToken = generateRefreshToken(user);
    await userModel.findByIdAndUpdate(user._id, {
      refreshToken,
      refreshTokenExpires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
    });
    // 设置 Refresh Token 为 HTTP-only Cookie
    res.cookie('maxtoken', refreshToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict',
      maxAge: 7 * 24 * 60 * 60 * 1000,
    });
    res.json({ code: 200, accessToken, user, msg: '登录成功' });
    console.log(accessToken);
  } catch (error) {
    console.error('Login Error:', error);
    res.status(500).json({ code: -1, message: '服务器错误，请稍后再试' });
  }
});

router.post("/getuser", async (req, res) => {
  // console.log(req.rawHeaders[9]);
  const token = req.rawHeaders[9].split(" ")
  // console.log(token[1]);
  const newtoken = jwt.verify(token[1], secret)
  console.log(newtoken);
  const user = await userModel.findOne({ _id: newtoken.id })
  console.log(user);

  // const token = req.headers
  // console.log(token);
  res.send({
    code: 200,
    user
  })
})




// 刷新 token 接口
router.post('/refresh', async (req, res) => {
  console.log('[refresh] cookie中的refreshToken:', refreshToken);
  try {
    const decoded = jwt.verify(refreshToken, secret);
    console.log('[refresh] jwt.verify通过, decoded:', decoded);
    const user = await userModel.findById(decoded.id);
    console.log('[refresh] 数据库查到的user:', user);
    if (!user || user.refreshToken !== refreshToken || user.refreshTokenExpires < new Date()) {
      console.log('[refresh] refreshToken校验失败', {
        user: !!user,
        dbToken: user && user.refreshToken,
        cookieToken: refreshToken,
        expires: user && user.refreshTokenExpires,
        now: new Date()
      });
      return res.status(401).json({ code: 401, message: 'Refresh Token 无效或已过期' });
    }
    // ...
  } catch (error) {
    console.error('[refresh] jwt.verify异常:', error);
    res.status(401).json({ code: 401, message: '刷新 token 失败' });
  }
});

// 兼容旧接口 /refresh-token
router.post('/refresh-token', async (req, res) => {
  try {
    const refreshToken = req.cookies.maxtoken || req.body.RefreshToken; // 支持 Cookie 和 Body
    if (!refreshToken) {
      return res.status(400).json({ code: 400, message: 'Refresh Token 缺失' });
    }

    const decoded = jwt.verify(refreshToken, secret);
    const user = await userModel.findById(decoded.id);
    if (!user || user.refreshToken !== refreshToken || user.refreshTokenExpires < new Date()) {
      return res.status(401).json({ code: 401, message: 'Refresh Token 无效或已过期' });
    }

    const newAccessToken = generateAccessToken(user);
    res.json({ code: 200, AccessToken: newAccessToken });
  } catch (error) {
    console.error('Refresh Error:', error);
    res.status(401).json({ code: 401, message: '刷新 token 失败' });
  }
});



const tencentcloud = require('tencentcloud-sdk-nodejs-iai');

const IaiClient = tencentcloud.iai.v20200303.Client;
const clientConfig = {
  credential: {
    secretId: "AKID0wtlSxGOL6ez72jDUZUDk5D7qNhokTzI",
    secretKey: "8LUSFqGVdaLtFQN9h4D9sNOH1EJBsSp0"
  },
  region: 'ap-beijing',
  profile: {
    httpProfile: {
      endpoint: 'iai.ap-beijing.tencentcloudapi.com',
    },
  },
};
const client = new IaiClient(clientConfig);


// 引入腾讯云人脸识别包


// 活体检测
router.post('/faceLogin', async function (req, res) {
  const base64 = req.body.base64; //base64是前端传递过来要进行对比的照片的base64格式
  console.log('[faceLogin] 请求收到，base64长度:', base64 ? base64.length : '无');
  // const IaiClient = tencentcloud.iai.v20200303.Client;
  // const clientConfig = {
  //   credential: {
  //     //密钥和id值  https://console.cloud.tencent.com/cam/capi获取秘钥和id值
  //     secretId: 'AKID0wtiSxGOL6ez72jDUZUDk5D7qNhokTzI',
  //     secretKey: '8LUSFqGVdaLtFQN9h4D9SNOH1EJBSSp0',
  //   },
  //   region: 'ap-beijing', //人脸识别库的地区  华北地区-北京
  //   profile: {
  //     httpProfile: {
  //       endpoint: 'iai.tencentcloudapi.com',
  //     },
  //   },
  // };



  // 实例化要请求产品的client对象,clientProfile是可选的
  // const client = new IaiClient(clientConfig);
  // 先进行静态活体检测  再进行人脸匹配

  client.DetectLiveFace({ Image: base64 }).then(
    (data) => {
      console.log('[faceLogin] 活体检测结果:', data);
      if (data.IsLiveness) {
        //活体检测通过
        face(client, base64, res)
      } else {
        console.log('[faceLogin] 活体检测未通过');
        res.status(402).json({
          code: 402,
          msg: '未通过活体检测'
        })
      }
    },
    (err) => {
      console.error('[faceLogin] 活体检测异常:', err);
      res.status(402).json({ code: 402, msg: '活体检测异常', detail: err.message })
    }
  );
});




// 人脸识别
async function face(client, base64, res) {
  const params = {
    GroupIds: ['1011'], // 替换为你的人员库ID
    Image: base64,
    NeedPersonInfo: 1,
    QualityControl: 0,
    FaceMatchThreshold: 85,
  };
  console.log('[faceLogin] 开始人脸识别，参数:', params);
  const { Results } = await client.SearchFaces(params);
  console.log('[faceLogin] 人脸识别结果:', Results);
  if (Results[0].Candidates.length === 0) {
    console.log('[faceLogin] 没有匹配到候选人');
    res.status(402).json({
      code: 402,
      msg: '该人员没有注册',
    });
    return;
  }
  const { FaceId, Gender, PersonId, PersonName } = Results[0].Candidates[0];
  console.log('[faceLogin] 识别到候选人:', { FaceId, Gender, PersonId, PersonName });

  // 查找数据库用户
  console.log(PersonId);

  const user = await userModel.findOne({ PersonId: PersonId });
  console.log('[faceLogin] 数据库查找用户:', user);
  if (!user) {
    console.log('[faceLogin] 未找到对应用户:', PersonName);
    res.status(402).json({
      code: 402,
      msg: '未找到对应用户',
    });
    return;
  }
  console.log(user);
  // 生成 accessToken
  const accessToken = jwt.sign({ id: user._id }, secret, { expiresIn: '15m' });
  // 生成 refreshToken
  const refreshToken = jwt.sign({ id: user._id }, secret, { expiresIn: '7d' });
  // 更新数据库
  await userModel.findByIdAndUpdate(user._id, {
    refreshToken,
    refreshTokenExpires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
  });
  console.log('[faceLogin] 已更新用户refreshToken');
  // 设置 refreshToken 到 httpOnly cookie
  res.cookie('maxtoken', refreshToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    maxAge: 7 * 24 * 60 * 60 * 1000,
  });
  console.log('[faceLogin] 已设置cookie');

  res.json({
    code: 0,
    data: {
      FaceId,
      Gender,
      PersonId,
      PersonName,
      user,
    },
    accessToken,
    msg: '识别成功',
  });
  console.log('[faceLogin] 登录成功，返回accessToken');
}



// 注册人脸接口
router.post('/registerFace', async (req, res) => {
  const { userId, name, base64 } = req.body;
  const params = {
    PersonId: userId,
    PersonName: name,
    GroupId: 'tg2775571759',
    Image: base64,
  };

  try {
    await client.CreatePerson(params);
    res.json({ code: 0, msg: '注册成功' });
  } catch (error) {
    console.error('Register Error:', error);
    res.status(500).json({ code: -1, msg: '注册失败', error: error.message });
  }
});



//邮箱号发送验证码
const transporter = nodemailer.createTransport({
  host: 'smtp.qq.com',
  port: 465,
  secure: true,
  auth: {
    user: process.env.EMAIL_USER,
    pass: process.env.EMAIL_PASS
  },
  logger: true, // 启用日志
  debug: true   // 显示调试信息
});

console.log('SMTP配置验证:', {
  user: process.env.EMAIL_USER ? '已设置' : '未设置',
  pass: process.env.EMAIL_PASS ? '已设置' : '未设置'
});

// 存储验证码和token
const verificationCodes = new Map();
const resetTokens = new Map(); // 添加这行

router.post('/send-login-code', async (req, res) => {
  const { email } = req.body;
  console.log(email);

  try {
    // 检查用户是否存在
    const user = await userModel.findOne({ email: email });
    if (!user) {
      return res.status(404).json({ code: 404, message: '该邮箱未注册' });
    }

    // 生成6位数字验证码
    const code = Math.floor(100000 + Math.random() * 900000);
    const expiresAt = Date.now() + 5 * 60 * 1000;
    verificationCodes.set(email, { code, expiresAt });

    // 发送邮件
    const info = await transporter.sendMail({
      from: `"系统管理员" <${process.env.EMAIL_USER}>`,
      to: email,
      subject: '验证码',
      html: `
        <div style="font-family: Arial, sans-serif;">
          <h2 style="color: #1890ff;">密码重置验证码</h2>
          <p>您的验证码是：<strong style="font-size: 18px;">${code}</strong></p>
          <p>有效期5分钟，请勿泄露给他人</p>
        </div>
      `
    });

    console.log('邮件已发送:', info.messageId);
    res.json({ code: 200, message: '验证码已发送' });

  } catch (error) {
    console.error('邮件发送失败详情:', {
      error: error.message,
      stack: error.stack,
      env: {
        EMAIL_USER: process.env.EMAIL_USER,
        EMAIL_PASS: process.env.EMAIL_Pass ? '******' : '未设置'
      }
    });
    res.status(500).json({
      code: 500,
      message: '发送验证码失败',
      detail: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

// 2. 验证验证码并生成重置token
router.post('/verify-code', (req, res) => {
  const { email, code } = req.body;
  console.log('收到验证请求:', { email, code });

  if (!email || !code) {
    console.log('验证失败: 参数不完整', { email, code });
    return res.status(400).json({ code: 400, message: '参数不完整' });
  }

  const record = verificationCodes.get(email);
  console.log('验证码记录:', record);

  if (!record) {
    console.log('验证失败: 未找到验证码记录', { email });
    return res.status(400).json({ code: 400, message: '请先获取验证码' });
  }

  if (record.expiresAt < Date.now()) {
    console.log('验证失败: 验证码过期', { email, expiresAt: record.expiresAt });
    verificationCodes.delete(email);
    return res.status(400).json({ code: 400, message: '验证码已过期' });
  }

  if (parseInt(code) !== record.code) {
    console.log('验证失败: 验证码不匹配', {
      provided: parseInt(code),
      expected: record.code
    });
    return res.status(400).json({ code: 400, message: '验证码错误' });
  }

  // 生成重置token
  const token = crypto.randomBytes(32).toString('hex');
  resetTokens.set(token, email);
  verificationCodes.delete(email);

  res.json({ code: 200, message: '验证成功', data: { token } });
});

router.post('/update', async (req, res) => {
  
  
  const { _id, ...updateData } = req.body;
  if (!_id) {
    return res.status(400).json({ code: 400, msg: '缺少 _id' });
  }
  try {
    const updatedUser = await userModel.findByIdAndUpdate(
      _id,
      updateData,
      { new: true }
    );
    if (!updatedUser) {
      return res.status(404).json({ code: 404, msg: '用戶不存在' });
    }
    res.json({ code: 200, user: updatedUser, msg: '用戶資訊更新成功' });
  } catch (err) {
    res.status(500).json({ code: 500, msg: '伺服器錯誤', error: err.message });
  }
});



module.exports = router;